package com.itunic.cloud.configuration;

import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 提供一个缺省的端点。
 * 用于验证token的有效性及用户的OAuth的信息
 * @author Sean
 */
@FrameworkEndpoint
public class IntrospectEndpoint {
    TokenStore tokenStore;

    IntrospectEndpoint(TokenStore tokenStore) {
        this.tokenStore = tokenStore;
    }

    @PostMapping("/introspect")
    @ResponseBody
    public Map<String, Object> introspect(@RequestParam("token") String token) {

        //在token store中读取 access token
        OAuth2AccessToken accessToken = this.tokenStore.readAccessToken(token);
        Map<String, Object> attributes = new HashMap<>();
        //判断token是否合法
        if (accessToken == null || accessToken.isExpired()) {
            attributes.put("active", false);
            return attributes;
        }

        //如果合法，将构造出token的相信信息
        OAuth2Authentication authentication = this.tokenStore.readAuthentication(token);
        attributes.put("active", true);
        //token的过期时间
        attributes.put("exp", accessToken.getExpiration().getTime());
        // token的 权限范围
        attributes.put("scope", accessToken.getScope().stream().collect(Collectors.joining(" ")));
        /**
         * 权限对象名称
         */
        attributes.put("sub", authentication.getName());
        return attributes;
    }
}